package com.woniuxy.health.aspect;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.health.manager.service.IOperationLogService;
import com.woniuxy.health.model.manager.OperationLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.elasticsearch.common.inject.Inject;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.stream.Stream;

import static com.baomidou.mybatisplus.core.toolkit.SystemClock.now;

//@Component
//@Aspect
public class LogAspect {
    @Resource
    private ThreadLocal<String> threadLocal;

    @Resource
    private IOperationLogService iOperationLogService;

    @Resource
    private IOperationLogService logService;


    @Around(value = "execution(* * ..*Controller.*(..))")
    @Order(0)
    public Object allMethodLog(ProceedingJoinPoint point) {
        Object returnMethod = null;
        //创建日志对象
        OperationLog log = new OperationLog();
        try {
            //判断threadLocal是否为null
            if (threadLocal.get() != null) {
                String[] split = threadLocal.get().split("#");
                String ipAddress = split[0];
                String account = split[1];
                log = log.setOperIp(ipAddress).setOperAccount(account);
            }
            String mehtodName = point.getSignature().getName();
            log.setOperMethodName(mehtodName);
            log.setOperTime(new Timestamp(now()));
            //执行目标方法
            returnMethod = point.proceed();
            //设置成功状态
            log.setState((byte) 1);
        } catch (Throwable e) {
            //设置失败状态
            log.setState((byte) 0);
            //抛出异常
            throw new RuntimeException(e);
        } finally {
            //构建日志对象
            iOperationLogService.save(log);
            return returnMethod;
        }
    }
}
